var _pagination = null;
var cache = null;
var _sceneId;
var lock = false;
$(function() {
	initImage();
});

//初始化图片查看组件
function initImage() {
	Shadowbox.init();
	window.openImage = function(url) {
		Shadowbox.open({
			content : url,
			player : 'img'
		});
	};
}

/**
 * 查询
 */
function search() {
	var title = $("#searchTitle").val();
	_pagination = new Pagination({
		url : '../qrcode/find/list',
		data : {
			title : title
		},
		success : printListToPage,
		pagerHandler : 'pager'
	});
}

/**
 * 显示
 */
function printListToPage(rst) {

	var response = new qmsk.Response(rst);
	cache = response;
	qmsk.dataTable({
		tbodyId : 'columnList',
		heads : ["sceneId", "title", "type", "url", "counter", "sceneId"],
		response : response,
		handler : [[2, typeHandler], [3, imageHandler], [5, updateButton]],
		sup : ['sup', '共 [index] 条']
	});

}

function typeHandler(type, row) {
	if (type == 0) {
		return "永久有效";
	} else {
		return "临时有效";
	}
}

function imageHandler(url, row) {
	return "<a href='#' style='text-decoration:underline; color: green;' onclick=\"openImage('" + url + "')\">查看</a>";
}

function updateButton(columnId, row) {
	return "<input type='button' class='common_btn' value='修改' onClick='toUpdate(" + row + ")'/>";
}

/**
 * 打开添加弹出层
 */
function showAddPanel() {

	$("#saveButton").unbind('click');
	$("#saveButton").bind('click', add);

	$("#window_change input[type='text']").val('');

	$("#window_change,#yinying1").show();
	addMargin($("#window_change"));
}

/**
 * 隐藏添加弹出层
 */
function hideAddPanel() {
	$("#window_change,#yinying1").hide();
}

function add() {

	if (lock) {
		return;
	} else {
		lock = true;
	}

	var title = $("#title").val();
	var type = $("#type").val();

	qmsk.post("../qrcode/insert", {
		title : title,
		type : type
	}, function() {
		lock = false;
		artSuccess("添加成功！");
		hideAddPanel();
		if (_pagination) {
			_pagination.reload();
		}
	});
}

function toUpdate(row) {

	var response = cache;
	_sceneId = response.getValue("sceneId", row);
	var title = response.getValue("title", row);
	var type = response.getValue("type", row);
	$("#title").val(title);
	$("#type").val(type);
	$("#window_change,#yinying1").show();
	addMargin($("#window_change"));
	$("#saveButton").unbind('click');
	$("#saveButton").bind('click', update);

}

function update() {

	var title = $("#title").val();

	qmsk.post("../qrcode/update/" + _sceneId, {
		title : title
	}, function(respone) {
		artSuccess("更新成功！");
		$("#window_change,#yinying1").hide();
		_pagination.reload();
	});
}

